/*
 * To change this license header, choose License Headers in Project Properties. To change this
 * template file, choose Tools | Templates and open the template in the editor.
 */

package chalmers.game.subterranean.ui.view.world;

import chalmers.game.subterranean.event.Bus;
import chalmers.game.subterranean.event.events.world.AddActionBlockEvent;
import chalmers.game.subterranean.event.events.world.AddLevelEvent;
import chalmers.game.subterranean.event.events.world.DamageBlockEvent;
import chalmers.game.subterranean.event.events.world.DestroyBlockEvent;
import chalmers.game.subterranean.ui.view.world.level.Level;
import chalmers.game.subterranean.util.BlockType;
import chalmers.game.subterranean.util.options.Variables;
import com.google.common.eventbus.Subscribe;
import java.util.ArrayList;

import chalmers.game.subterranean.util.Position;
import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.scene.layout.GridPane;

/**
 * 
 * @author TH
 */
public class LevelGrid {
  public final GridPane grid;
  private final ArrayList<Level> levels;
  private final TranslateTransition mover;

  public LevelGrid(int size) {
    mover = new TranslateTransition();
    grid = new GridPane();

    levels = new ArrayList(size);
    mover.setNode(grid);
    mover.setDuration(Variables.ANIMATION_DURATION);
    Bus.INSTANCE.register(this);
  }

  @Subscribe
  public void addLevelHandler(AddLevelEvent evt) {
    Platform.runLater(() -> {
        Level newLevel = new Level();

        for (int y = 0; y < evt.blockTypes.length; y++) {
            for (int x = 0; x < evt.blockTypes[y].length; x++) {
                newLevel.add(evt.blockTypes[y][x], x, y);
            }
        }
        levels.add(newLevel);
        grid.add(newLevel.grid, 0, evt.depth);
    });
  }

  @Subscribe
  public void destroyBlockHandler(DestroyBlockEvent evt) {
    levels.get(evt.pos.depth).destroy(evt.pos.point);
  }

  @Subscribe
  public void damageBlockHandler(DamageBlockEvent evt) {
    levels.get(evt.pos.depth).damage(evt.pos.point);
  }

  @Subscribe
  public void addLadderHandler(AddActionBlockEvent evt) {
    BlockType type = evt.type;
    Position pos = evt.pos;
    Level lvl = levels.get(pos.depth);

    lvl.changeBlock(pos.point,type);

    /*switch(type.action){
      case LADDER:
        lvl.setLadder(pos.point);
        break;
      case TELEPORT:
       // lvl.setTeleportBLock(pos);
        break;
      case SHOP:
        //lvl.setShopBlock;
        break;
    } */

    try {
      //levels.get(evt.pos.depth).setLadder(evt.pos.point);
    } catch (Exception e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
                           // Templates.
    }
  }
}
